package org.myhibernate.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ObjectClone 
{
	public Object clone(Object obj)
	{
		if (obj==null) {
			return null;
		} 
		Object cloneObject=null;
		try {
			cloneObject=Class.forName(obj.getClass().getName()).newInstance();
			Field[] fields=obj.getClass().getDeclaredFields();
			Field field=null;
			String fieldName="";
			Object dataValue=null;
			PropertyDescriptor descriptor=null;
			Method readMethod =null,writeMethod=null;
			for (int i = 0; i < fields.length; i++) 
			{
				field=fields[i];
				fieldName=field.getName();
				try {
					 descriptor= new PropertyDescriptor(fieldName, obj.getClass());
					 readMethod = descriptor.getReadMethod();
					 dataValue=readMethod.invoke(obj);
					 writeMethod=descriptor.getWriteMethod();
					 writeMethod.invoke(cloneObject, dataValue);
				} catch (Exception e) {
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return cloneObject;
	}
	public Object sameCopy(Object fromObject,Object toObject)
	{
		if ((fromObject==null)||(toObject==null)) {
			return null;
		}
		Object cloneObject=null;
		try {
			Field[] fields=fromObject.getClass().getDeclaredFields();
			Field field=null;
			String fieldName="";
			Object dataValue=null;
			PropertyDescriptor descriptor=null;
			Method readMethod =null,writeMethod=null;
			for (int i = 0; i < fields.length; i++) 
			{
				field=fields[i];
				fieldName=field.getName();
				try {
					 descriptor= new PropertyDescriptor(fieldName, fromObject.getClass());
					 readMethod = descriptor.getReadMethod();
					 dataValue=readMethod.invoke(fromObject);
					 if (dataValue !=null)
					 {
						 PropertyDescriptor writeDescriptor=new PropertyDescriptor(fieldName, toObject.getClass());
						 writeMethod=writeDescriptor.getWriteMethod();
						 writeMethod.invoke(toObject, dataValue);
					 }
					// writeMethod=descriptor.getWriteMethod();
					// writeMethod.invoke(cloneObject, dataValue);
					
				} catch (Exception e) {
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return cloneObject;
	}
}
